package net.xdclass.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import net.xdclass.dto.AccountDTO;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import net.xdclass.util.JwtUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author 姜阿木
 * @date 2025/5/24 11:01
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<AccountDTO> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        // 处理option请求
        if(HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())){
            // 响应204内容为空
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }
        // 获取token
        String token = request.getHeader("token");
        if (token == null){
            // 请求中没有token
            token = request.getParameter("token");
        }
        // 如果存在token，解析token
        if (StringUtils.isNotBlank(token)){
            Claims claims = JwtUtil.checkLoginJWT(token);
            if (claims == null){
                // 如果token无效，返回未登录的错误信息
                CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
                return false;
            }
            // 从JWT里 获取用户信息
            Long accountId = Long.valueOf(claims.get("accountId") + "");
            String username = claims.get("username").toString();
            AccountDTO accountDTO = AccountDTO.builder()
                    .id(accountId)
                    .username(username)
                    .build();
            // 将用户信息存入 ThreadLocal
            threadLocal.set(accountDTO);
            return true;
        }
        // 如果不存在token，返回未登录的错误信息
        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
        return false;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理 ThreadLocal 中的用户信息
        threadLocal.remove();
    }
}
